package cn.yll.user.controller;


import cn.yll.api.user.request.UserCashRequest;
import cn.yll.api.user.request.UserPwdLoginRequest;
import cn.yll.common.exception.BsErrEnum;
import cn.yll.common.module.RestModel;
import cn.yll.common.utils.CopierUtil;
import cn.yll.common.utils.EncryptUtil;
import cn.yll.api.util.RestUtil;
import cn.yll.api.user.request.UserRegisterRequest;
import cn.yll.api.user.response.UserBaseResponse;
import cn.yll.user.entity.UserEntity;
import cn.yll.user.entity.UserExtendEntity;
import cn.yll.user.service.IUserExtendService;
import cn.yll.user.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;

import java.util.Objects;


/**
 * <p>
 * 商城用户表 前端控制器
 * </p>
 *
 * @author yll
 * @since 2022-08-01
 */
@RefreshScope
@RestController
@Api(tags = "商城用户表相关接口")
@RequestMapping("/user")
public class UserController extends BaseController {

    @Value("${user.pwd.salt}")
    private String userPwdSalt;
    @Autowired
    private IUserService userService;

    @Autowired
    private IUserExtendService userExtendService;

    @PostMapping("/register")
    @ApiOperation(value = "用户注册接口", notes = "参数必填")
    @Transactional(rollbackFor = Exception.class)
    public RestModel<UserBaseResponse> register(@RequestBody UserRegisterRequest user) {
        if (Objects.isNull(user)) {
            return RestUtil.error(BsErrEnum.PARAM_EMPTY);
        }
        UserEntity entity = CopierUtil.convertT(user, UserEntity.class);
        assert entity != null;
        entity.setCash(0);
        entity.setPassword(EncryptUtil.HmacMD5(entity.getPassword(), userPwdSalt));
        userService.save(entity);
        UserExtendEntity extendEntity = CopierUtil.convertT(user, UserExtendEntity.class);
        assert extendEntity != null;
        extendEntity.setUserId(entity.getId());
        userExtendService.save(extendEntity);
        return RestUtil.sucess(CopierUtil.convertT(entity, UserBaseResponse.class));
    }

    @PostMapping("validUserPwd")
    @ApiOperation(value = "校验用户密码接口", notes = "所有参数必填")
    public RestModel<UserBaseResponse> validUserPwd(@RequestBody UserPwdLoginRequest request) {
        if (Objects.isNull(request) || StringUtils.isAnyBlank(request.getUserName(), request.getPwd())) {
            return RestUtil.error(BsErrEnum.PARAM_EMPTY);
        }
        UserEntity user = userService.lambdaQuery().eq(UserEntity::getUserName, request.getUserName()).one();
        if (Objects.nonNull(user) && Objects.equals(user.getPassword(), EncryptUtil.HmacMD5(request.getPwd(), userPwdSalt))) {
            return RestUtil.sucess(CopierUtil.convertT(user, UserBaseResponse.class));
        }
        return RestUtil.error(BsErrEnum.PWD_ERROR);
    }

    @PostMapping("cash")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "用户充值或消费接口", notes = "金额正数表示充值，负数代表消费")
    public RestModel<Boolean> addCash(@RequestBody UserCashRequest request) {
        if (Objects.isNull(request) || Objects.isNull(request.getUserId()) || Objects.isNull(request.getCash())) {
            return RestUtil.error(BsErrEnum.PARAM_EMPTY);
        }
        LambdaUpdateWrapper<UserEntity> updateWrapper = Wrappers.lambdaUpdate(UserEntity.class).eq(UserEntity::getId, request.getUserId());
        if (request.isPay()) {
            updateWrapper.setSql("cash = cash - " + request.getCash());
            updateWrapper.gt(UserEntity::getCash, request.getCash());
        } else {
            updateWrapper.setSql("cash = cash + " + request.getCash());
        }
        boolean result = userService.update(updateWrapper);
        if (!result && request.isPay()) {
            return RestUtil.error("余额不足，请先充值");
        }
        return RestUtil.sucess(result);
    }

    @GetMapping("/getById/{id}")
    @ApiOperation(value = "根据用户ID查询基本信息", notes = "Id必填")
    public RestModel<UserBaseResponse> getUserById(@PathVariable("id") Long userId) {
        if (Objects.isNull(userId)) {
            return RestUtil.error(BsErrEnum.PARAM_EMPTY);
        }
        UserEntity userEntity = userService.getById(userId);
        return RestUtil.sucess(CopierUtil.convertT(userEntity, UserBaseResponse.class));
    }

    @GetMapping("/getByUserName/{userName}")
    @ApiOperation(value = "根据用户名查询基本信息", notes = "登录用户名必填")
    public RestModel<UserBaseResponse> getByUserName(@PathVariable("userName") String userName) {
        if (StringUtils.isBlank(userName)) {
            return RestUtil.error(BsErrEnum.PARAM_EMPTY);
        }
        UserEntity userEntity = userService.lambdaQuery().eq(UserEntity::getUserName, userName).one();
        return RestUtil.sucess(CopierUtil.convertT(userEntity, UserBaseResponse.class));
    }

    @GetMapping("/getByPhone/{phone}")
    @ApiOperation(value = "根据手机号查询用户信息", notes = "手机号必填")
    public RestModel<UserBaseResponse> getByPhone(@PathVariable("phone") String phone) {
        if (StringUtils.isBlank(phone)) {
            return RestUtil.error(BsErrEnum.PARAM_EMPTY);
        }
        UserEntity userEntity = userService.lambdaQuery().eq(UserEntity::getPhone, phone).one();
        return RestUtil.sucess(CopierUtil.convertT(userEntity, UserBaseResponse.class));
    }
}
